package com.szh.mysobproject.ui.fragment

import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import by.kirich1409.viewbindingdelegate.viewBinding
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import com.szh.mysobproject.R
import com.szh.mysobproject.action.StatusAction
import com.szh.mysobproject.app.AppFragment
import com.szh.mysobproject.databinding.VipListFragmentBinding
import com.szh.mysobproject.other.GridSpaceDecoration
import com.szh.mysobproject.ui.activity.CopyActivity
import com.szh.mysobproject.ui.adapter.VipUserListAdapter
import com.szh.mysobproject.util.dp
import com.szh.mysobproject.util.isEmpty
import com.szh.mysobproject.viewmodel.UserViewModel
import com.szh.mysobproject.widget.StatusLayout

/**
 * @author : create by  szh
 * @date : 2022/7/6 14:15
 * @desc :vip用户列表
 */

class VipListFragment : AppFragment<CopyActivity>(), StatusAction, OnRefreshListener {

    private val mBinding: VipListFragmentBinding by viewBinding()
    private val mUserViewModel by viewModels<UserViewModel>()
    private var mAdapter = VipUserListAdapter()

    override fun getLayoutId(): Int = R.layout.vip_list_fragment

    override fun initView() {
        mBinding.rc.apply {
            adapter = mAdapter
            layoutManager = GridLayoutManager(context, 3)
            addItemDecoration(GridSpaceDecoration(4.dp))
        }
    }

    override fun initData() {
        loadVipUserList()
    }

    private fun loadVipUserList() {
        showLoading()
        mUserViewModel.getVipUserList().observe(this) {
            mBinding.refreshLayout.finishRefresh()
            val vipUserSummaryList = it.getOrElse {
                showError {
                    loadVipUserList()
                }
                return@observe
            }
            mAdapter.setData(vipUserSummaryList)
            if (mAdapter.isEmpty()) {
                showEmpty()
            } else {
                showComplete()
            }
        }
    }

    override fun initEvent() {
        mBinding.refreshLayout.setOnRefreshListener(this)
    }

    override fun getStatusLayout(): StatusLayout = mBinding.hlVipUserListHint

    override fun onRefresh(refreshLayout: RefreshLayout) {
        loadVipUserList()
    }

    companion object {
        fun newInstance(): VipListFragment {
            return VipListFragment()
        }
    }
}